<template>
  <div class="full flex-cen">
    <el-form
      class="bg-white"
      :class="$style.ruleform"
      ref="ruleFormRef"
      :model="ruleForm"
    >
      <div :class="$style.title">微前端示例地址</div>
      <el-form-item
        prop="name"
        :rules="[{ required: true, trigger: 'change', message: '请输入用户名' }]"
      >
        <el-input
          v-model="ruleForm.name"
          maxlength="20"
          placeholder="账号随便填"
        ></el-input>
      </el-form-item>
      <el-form-item
        prop="phone"
        @keyup.enter="handleSubmit"
        :rules="[{ validator: validatPhone, trigger: 'change' }]">
        <el-input
          v-model="ruleForm.phone"
          placeholder="手机号 随便一个号码"
          maxlength="11"
        ></el-input>
      </el-form-item>
      <el-button
        style="width: 100%"
        type="primary"
        @click="handleSubmit"
      >提交</el-button>
    </el-form>
  </div>
</template>

<script setup>

import { reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

const ruleFormRef = ref(null)
const store = useStore()
const router = useRouter()

const ruleForm = reactive({
  name: '',
  phone: ''
})

// 验证手机号码
const validatPhone = (rule, value, callback) => {
  if (!(/^1\d{10}$/.test(value))) {
    callback(new Error('请输入11位手机号'))
    return
  }
  callback()
}

// 提交
const handleSubmit = () => {
  ruleFormRef.value.validate((valid) => {
    if (!valid) { return '' }
    store.commit('SET_USER_INFO', {
      name: ruleForm.name,
      phone: ruleForm.phone
    })
    localStorage.setItem('base_user', JSON.stringify({
      name: ruleForm.name,
      phone: ruleForm.phone
    }))
    router.push('/home')
  })
}

</script>
<style module>
.ruleform {
  width: 400px;
  padding: 40px 30px;
}
.title {
  padding-bottom: 30px;
  font-size: 30px;
  text-align: center;
}
</style>
